package yxy.cherry.paycenter.servlet.channel.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import yxy.apple.logger.Logger;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.charge;
import yxy.cherry.paycenter.channelmodule.ActType;
import yxy.cherry.paycenter.channelmodule.sdk_jh.PayMoudle_jh;
import yxy.cherry.paycenter.channelmodule.weixin.PayMoudle_weixin;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.cherry.paycenter.util.wxUtil;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.module.OrderInfoModule;

/**
 * 微信 - 安卓 - 支付通知
 * @author Dell
 *
 */
public class Servlet_WeiXinAndroid extends Servlet {

	private static final Logger logger = Logger.create(Servlet_WeiXinAndroid.class);
	
	public static final String query_url = "https://api.weixin.qq.com/wxa/business/getpayfororder?access_token=%S";
	
	public static final String SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

	public static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
	
	private static final String success = "OK";	//交易结果 成功
	private static final String fail = "FAIL";	//交易结果 失败
	
	@Override
	public String getUrl() {
		return "/sdk_" + getChannel() + PayMoudle_weixin.android;
	}
	
	public Servlet_WeiXinAndroid() {
//		SdkService.getInstance().addServlet("/jh", new Servlet_jh());
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		logger.info("Servlet_WeiXinAndroid req :" + req);
		JSONObject infoobj = HttpUtil.getParseJSON(req);
		logger.info("Servlet_WeiXinAndroid infoobj :" + infoobj);
		
		Object[] objs = infoobj.keySet().toArray();
		String jsonstr = objs[0].toString();
		JSONObject json = JSON.parseObject(jsonstr);
		logger.info("Servlet_WeiXinAndroid json :" + json);
		
		String myorderid = json.getString("myorderid");	//游戏订单号
		String paymount = json.getString("paymount");	//实付金额 
		String goodsid = json.getString("goodsid");	//道具id
		String time = json.getString("time");		//时间戳
		
		String sign = json.getString("sign");		
		String newsign = getSign(myorderid, paymount, goodsid, time);
		
		if(!newsign.equals(sign)) {
			returnInfo(fail, resp);
			return;
		}

		orders o = ordersDao.getOrderByMyorderid(myorderid);
		if(o == null) {
			returnInfo(fail, resp);
			return;
		}
		
		if(o.getOrderstate() == OrderInfoModule.orderinfofinish) {
			returnInfo(success, resp);
			return;
		}
		
		o.setUpdatetime(new Date());
		o.setSubchannel(o.getChannel());
		o.setOrderstate(OrderInfoModule.orderinfofinish);
		o.setPayamount(Integer.valueOf(paymount));
		ordersDao.update(o);
		
		ActType at = ActType.getat(o.getActtype());
		PayMoudle_jh am = new PayMoudle_jh();
		ArrayList<Currency> curs = am.getRewardInfoByType(o.getPlayercode(), at, o.getGoodsid());
		charge charge = DataCenter.getData(o.getGoodsid(), charge.class);
		am.createOrderInfoModule(o, curs, charge.getVipexp(), o.getGoodsprice());
	
		returnInfo(success, resp);
	}

	/**
	 * 返回信息到渠道
	 * 
	 * @param data
	 * @param resp
	 */
	public void returnInfo(String data, HttpServletResponse resp) {
		PrintWriter pw = null;
		resp.addHeader("Access-Control-Allow-Origin", "*");

		try {
			pw = resp.getWriter();
			pw.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pw != null)
				pw.close();
		}
	}

	@Override
	public String getChannel() {
		return SdkChannel.sdk_weixin;
	}
	
	private String getReturnXml(String code, String msg) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("code", code);
		map.put("msg", msg);
		
		return wxUtil.mapToXml(map, false);
	}
	
	private String getSign(String myorderid, String paymount, String goodsid, String time) {
//		String myorderid = "";	//游戏订单号
//		String paymount = "";	//实付金额 
//		String goodsid = "";	//道具id
//		String time = "";		//时间戳
		
//		String key = "weixincpverify";
		
		String signstr = "myorderid" + myorderid + "paymount" + paymount + "goodsid" + goodsid +"time" + time + "weixincpverify";
		String sign = HttpUtil.getMD5(signstr).toLowerCase();
		return sign;
	}
	
//	public static void main(String[] args) {
//		JSONObject json = JSON.parseObject("{\"myorderid\":\"20210528159193233094\",\"goodsid\":\"93001\",\"sign\":\"560172cf20c740875ec1a00cab129f67\",\"time\":\"1622201553436\",\"paymount\":\"100\"}");
//		String myorderid = json.getString("myorderid");	//游戏订单号
//		String paymount = json.getString("paymount");	//实付金额 
//		String goodsid = json.getString("goodsid");	//道具id
//		String time = json.getString("time");		//时间戳
//		
//		String sign = json.getString("sign");		
////		String newsign = getSign(myorderid, paymount, goodsid, time);
//		String signstr = "myorderid" + myorderid + "paymount" + paymount + "goodsid" + goodsid +"time" + time + "weixincpverify";
//		String newsign = HttpUtil.getMD5(signstr);
//		
//	}
}
